package com.compass.mobile.ui.dialog

import AppManager
import LogUtil
import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.DatePicker
import android.widget.RadioButton
import android.widget.Toast
import androidx.fragment.app.FragmentActivity
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.compass.mobile.R
import com.compass.mobile.callback.OnCustomButtonClick
import com.compass.mobile.callback.OnInquiryButtonClick
import com.compass.mobile.databinding.DialogAddInquiryBinding
import com.compass.mobile.databinding.DialogInquiryBinding
import com.compass.mobile.framework.base.BaseActivity
import com.compass.mobile.framework.base.BaseDialog
import com.compass.mobile.framework.base.BaseDialogFragment
import com.compass.mobile.framework.decoration.NormalItemDecoration
import com.compass.mobile.framework.ext.gone
import com.compass.mobile.framework.ext.invisible
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.ext.visible
import com.compass.mobile.framework.utils.DateUtils
import com.compass.mobile.framework.utils.FocusViewUtils
import com.compass.mobile.framework.utils.NumberAndCharInputFilter
import com.compass.mobile.framework.utils.QRCodeDealUtils
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.EquityBean
import com.compass.mobile.models.InquiryInfo
import com.compass.mobile.models.MedicalRecordReport
import com.compass.mobile.presenters.ReportUploadPresenter
import com.compass.mobile.ui.adapter.PictureAdapter
import com.compass.mobile.widget.MyBridgeAdapter
import com.google.android.material.datepicker.MaterialDatePicker
import com.google.android.material.timepicker.MaterialTimePicker
import com.google.android.material.timepicker.TimeFormat
import dp2px
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import setUrlCircle
import setUrlRound
import toJson
import java.util.Calendar
import java.util.Date

/**
 * Description： 添加问诊弹窗
 * Date:2024/7/16 14:36
 */
class InquiryAddDialog {
    class Builder(
        activity: FragmentActivity,
        private var benefits: MutableList<EquityBean>?,
        private var onCustomButtonClick: OnInquiryButtonClick?,
        private var codeUrl: String?
    ) :
        BaseDialogFragment.Builder<Builder>(activity) {
        private val mBinding: DialogAddInquiryBinding =
            DialogAddInquiryBinding.inflate(LayoutInflater.from(activity))

        //        private var benefitId: String? = null
        init {
            initView()
        }

        private var ifReturnVisit = -1 //是否复诊
        private var illnessDuration = "" //患病时长
        private var lastDiagnosis = "" //上次确诊诊断
        private var lastVisitHospital = "" //上次就医医院
        private var lastVisitDate = "" //上次就诊日期
        private var ifSanity = -1 //是否神志清楚
        private var inHospitalHere = -1 //曾在本院住院
        private var inpatientDepartment = "" // 住院科室
        private var inpatientDate = "" //住院日期
        private var diseaseDescriptionText = "" // 住院描述
        private lateinit var imgLists: ArrayList<String>
        private lateinit var pictureAdapter: PictureAdapter
        private fun initView() {
            setContentView(mBinding.root)
            setWidth((AppManager.getScreenHeightPx() * 0.9).toInt())
            setHeight((AppManager.getScreenWidthPx() * 0.95).toInt())
            setAnimStyle(BaseDialog.AnimStyle.DEFAULT)
            setGravity(Gravity.CENTER)
            setCancelable(true)
            imgLists = arrayListOf()
            initRcyPicture()
            codeUrl?.let {
                LogUtil.e("codeUrl===$codeUrl")
                mBinding.ivQrcode.setImageBitmap(
                    QRCodeDealUtils.generateQRCodeWithoutMargin(
                        it,
                        dp2px(400f),
                        dp2px(400f)
                    )
                )
            }
            // 设置就诊人
            setDefaultPatientInfo()
//            FocusViewUtils.scaleView(mBinding.tvLastDate,0)
//            FocusViewUtils.scaleView( mBinding.tvHostDate,0)
            mBinding.apply {
//                radioFirstVisit.setOnCheckedChangeListener()
                val filter = NumberAndCharInputFilter()
                mBinding.etIllnessDuration.filters = arrayOf(filter)
                radioFirstVisit.setOnCheckedChangeListener { group, checkedId ->
                    val radioButton = findViewById<RadioButton>(checkedId)
                    val mSelectedValue = radioButton.text.toString()

                    tvVisitContent.text = mSelectedValue

                    if (mSelectedValue == "是") {
                        //是
                        ifReturnVisit = 1
                        llLastHos.visible()
                        llLastDiagnosis.visible()
                        llLastData.visible()

                        llLastDiagnosisContent.visible()
                        llLastHosContent.visible()
                        llLastDataContent.visible()

                    } else {
                        //否
                        ifReturnVisit = 0
                        llLastHos.gone()
                        llLastDiagnosis.gone()

                        llLastData.gone()

                        llLastDiagnosisContent.gone()
                        llLastHosContent.gone()
                        llLastDataContent.gone()
                    }
                }


                radioIfSanity.setOnCheckedChangeListener { group, checkedId ->
                    val radioButton = findViewById<RadioButton>(checkedId)
                    val mSelectedValue = radioButton.text.toString()
                    tvIfSanity.text = mSelectedValue
                    if (mSelectedValue == "是") {
                        //是
                        ifSanity = 1
                    } else {
                        //否
                        ifSanity = 0
                    }
                }

                radioInHospitalHere.setOnCheckedChangeListener { group, checkedId ->
                    val radioButton = findViewById<RadioButton>(checkedId)
                    val mSelectedValue = radioButton.text.toString()
                    tvInHospitalHere.text = mSelectedValue
                    if (mSelectedValue == "是") {
                        //是
                        inHospitalHere = 1
//                        llDepartments.visible()
//                        llHosData.visible()
                    } else {
                        //否
                        inHospitalHere = 0
//                        llDepartments.gone()
//                        llHosData.gone()
                    }
                }

                tvLastDate.onClick {
                    showDateDialog(activity, 1)
                }
                tvHostDate.onClick {
                    showDateDialog(activity, 2)
                }
                tvUpdate.onClick {
                    onCustomButtonClick?.onButtonCallBack(2, null)

                }
                tvSave.onClick {
                    //保存按钮
                    val curActivity = activity as BaseActivity
                    //对数据进行检验，检验通过之后回调
                    illnessDuration = mBinding.etIllnessDuration.text.toString().trim()

                    if (ifReturnVisit == -1) {
                        curActivity.showToast("请选择是否复诊")
                        return@onClick
                    }
                    if (illnessDuration.isEmpty()) {
                        curActivity.showToast("请输入患病时长")
                        return@onClick
                    }

                    lastDiagnosis = mBinding.etLastDiagnosis.text.toString().trim() //上次诊断
                    lastVisitHospital = "本院"

//                    lastVisitDate =

                    if (ifReturnVisit == 1) {
                        //是复诊
                        if (lastDiagnosis.isEmpty()) {
                            curActivity.showToast("请输入上次确诊诊断")
                            return@onClick
                        }
                        if (lastVisitDate.isEmpty()) {
                            curActivity.showToast("请选择上次就诊日期")
                            return@onClick
                        }
                    } else {
                        //否复诊
                    }
                    if (ifSanity == -1) {
                        curActivity.showToast("请选择是否神志清楚")
                        return@onClick
                    }
                    inpatientDepartment = etDept.text.toString().trim()
                    if (inHospitalHere == -1) {
                        curActivity.showToast("请选择是否再本院住院")
                        return@onClick
                    } else if (inHospitalHere == 1) {

//                        if(inpatientDepartment.isEmpty()){
//                            curActivity.showToast("请输入住院科室")
//                            return@onClick
//                        }
//                        if(inpatientDepartment.isEmpty()){
//                            curActivity.showToast("请输入住院科室")
//                            return@onClick
//                        }
                    }
                    diseaseDescriptionText = etDescription.text.toString().trim()
                    if (diseaseDescriptionText.isEmpty()) {
                        curActivity.showToast("请输入病情描述")
                        return@onClick
                    }
                    //日期的格式要求是： yyyy-MM-dd HH:mm:ss

                    val inquiryInfo = InquiryInfo(
                        ifReturnVisit,
                        illnessDuration,
                        lastDiagnosis,
                        lastVisitHospital,
                        lastVisitDate,
                        ifSanity,
                        inHospitalHere,
                        inpatientDepartment,
                        inpatientDate,
                        diseaseDescriptionText,
                        diseaseDescription = imgLists
                    )
                    onCustomButtonClick?.onButtonCallBack(1, inquiryInfo)
//                    dismiss()
                }
            }

//            FocusViewUtils.scaleView(mBinding.llCode, 0)
//            FocusViewUtils.scaleView(mBinding.llEquityOrder, 0)
//            FocusViewUtils.scaleView(mBinding.llEquityWriteOff, 0)
//            mBinding.llEquityOrder.onClick {
//                //订购
//                onCustomButtonClick?.onButtonCallBack(1, null)
//                dismiss()
//
//            }
//            mBinding.llEquityWriteOff.onClick {
//                //核销
//                onCustomButtonClick?.onButtonCallBack(2, benefitId)
//                dismiss()
//            }
//            mBinding.llCode.onClick {
//                //扫码
//                onCustomButtonClick?.onButtonCallBack(3, null)
//                dismiss()
//
//            }
//            setEquity()
        }

        fun setEdit(isEdit: Boolean) {
            if (!isEdit) {
                mBinding.apply {
                    tvSave.gone()
                    tvTitleContent.visible()
                    clInquiryForm.gone()
                    clInquiryContent.visible()
                    tvLastDateContent.text = lastVisitDate
                    tvLastDiagnosisContent.text = lastDiagnosis
                    tvIllnessDurationContent.text = illnessDuration
                    tvDeptContent.text = inpatientDepartment
                    tvHostDateContent.text = inpatientDate
                    tvDescriptionContent.text = diseaseDescriptionText
                    tvStatusText.text = "扫描上面二维码进行支付"
                }
            }
        }

        private fun setDefaultPatientInfo() {
            if (UserInfoManager.isHaveDefPatient()) {
                val patientBean = UserInfoManager.getPatientInfo()
                patientBean?.let {
                    mBinding.apply {
                        avatar.setUrlRound(it.avatar, 5)
                        tvName.text = it.name
                        if (it.sex == "1") mBinding.tvSex.text =
                            "性别：男" else mBinding.tvSex.text = "性别：女"
                        tvAge.text = "年龄：${DateUtils.formatAge2(it.birthday)}"
                    }
                }
            }
        }

//        private fun setEquity() {
//            if (benefits.isNullOrEmpty()) {
//                mBinding.llEquityWriteOff.gone()
//            } else {
//                mBinding.llEquityWriteOff.visible()
//                val item = benefits?.get(0)
//                item?.let {
//                    benefitId = it.id
//                    mBinding.tvEquity.text = "${it.benefitName}数量：${getNumber(item)}"
//
//                }
//
//
//            }
//        }

//        private fun getNumber(equityBean: EquityBean): String? {
//            // type={1图文 2电话 3视频}
//
//            return when (inquiryType) {
//                "1" -> equityBean.txtNumber
//                "2" -> equityBean.phoneNumber
//                "3" -> equityBean.videoNumber
//                else -> {
//                    "0"
//                }
//            }
//        }

        private fun showDateDialog(activity: FragmentActivity, type: Int) {
            // 获取当前日期
            val calendar = Calendar.getInstance()
            val year = calendar.get(Calendar.YEAR)
            val month = calendar.get(Calendar.MONTH)
            val day = calendar.get(Calendar.DAY_OF_MONTH)

            val datePickerDialog =
                DatePickerDialog(activity, { view, selectedYear, selectedMonth, selectedDay ->
                    val selectedDate = "$selectedYear-${selectedMonth + 1}-$selectedDay"
                    if (type == 1) {
                        mBinding.tvLastDate.text = selectedDate
                        lastVisitDate = selectedDate
                    } else if (type == 2) {
                        mBinding.tvHostDate.text = selectedDate
                        inpatientDate = selectedDate
                    }
//                Toast.makeText(this, "Selected date: $selectedDate", Toast.LENGTH_SHORT).show()
                }, year, month, day)
            datePickerDialog.datePicker.maxDate = calendar.timeInMillis
            datePickerDialog.show()
        }
//            val datePicker = MaterialDatePicker.Builder.datePicker()
//                .setTitleText("选择日期")
//                .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
//                .build()
//
//            datePicker.addOnPositiveButtonClickListener { selection ->
//                val calendar = Calendar.getInstance()
//                calendar.timeInMillis = selection
//                val year = calendar.get(Calendar.YEAR)
//                val month = calendar.get(Calendar.MONTH) + 1
//                val day = calendar.get(Calendar.DAY_OF_MONTH)
//                if(type == 1){
//                    mBinding.tvLastDate.text = "${year}-${month}-${day}"
//                }else if(type == 2){
//                    mBinding.tvHostDate.text = "${year}-${month}-${day}"
//                }
//            }
//
//            datePicker.show(activity.supportFragmentManager , "DATE_PICKER")


        private fun initRcyPicture() {
            pictureAdapter = PictureAdapter(1)
            mBinding.rcyImg.apply {
                layoutManager = GridLayoutManager(activity, 4)
                adapter = pictureAdapter
                addItemDecoration(NormalItemDecoration().apply {
                    setBounds(top = 0, right = dpToPx(10), bottom = 0)
                })
            }
        }

        fun setImgLists(imgs: ArrayList<String>) {
            imgLists = imgs
//            if (imgLists.isEmpty()){
//                mBinding.rcyImg.gone()
//            }else{
//                mBinding.rcyImg.visible()
//            }
            pictureAdapter.setData(imgLists)
            LogUtil.d("imgs====${imgLists.toJson()}")
        }

        fun dismissDialog() {
            dismiss()
        }
    }


}